#include "server.h"

namespace cs
{
	server::server():
		logger("server")
	{
		boost_asio_tcp::endpoint endpoint(boost_asio_tcp::v4(), 6669);
		acceptor_.reset( new boost_asio_tcp::acceptor(io_service_, endpoint));

	}

	void server::run()
	{
		thread.reset(new boost::thread(boost::bind(&boost::asio::io_service::run, &io_service_)));
		start_accept();
	}

	void server::stop()
	{
		if ( !io_service_.stopped()) {
			io_service_.stop();
			thread->join();		
		}
	}

	server::~server()
	{
		stop();
	}

	void server::start_accept()
	{
		session_ptr new_session(new session(io_service_));
		acceptor_->async_accept(new_session->socket(),
			boost::bind(&server::handle_accept, this, new_session,
			boost::asio::placeholders::error));
	}

	void server::handle_accept(session_ptr session,
		const boost::system::error_code& error)
	{
		if (!error) {
			printf("New connection\n");
			session->start();
		} else {
			printf("%s\n", error.message());
		}
		
		start_accept();
	}

}